package com.km.sglototo.sys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.km.sglototo.sys.service.ISysOrgService;
import com.km.sglototo.sys.entity.SysOrg;
import com.km.sglototo.sys.entity.SysOrgNode;
import com.km.sglototo.sys.mapper.SysOrgMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author sglototo
* @date 2022-01-09
*/
@Service
public class SysOrgServiceImpl extends ServiceImpl
        <SysOrgMapper, SysOrg> implements ISysOrgService {

@Resource
private  SysOrgMapper sysOrgMapper;




    @Override
    public List<SysOrgNode> treeList() {
        List<SysOrg> sysOrgList = sysOrgMapper.selectList(new QueryWrapper<SysOrg>().orderByAsc("sortno"));
        List<SysOrgNode> result = sysOrgList.stream()
                .filter(permission -> permission.getParentid().equals(0))
                .map(permission -> covert(permission, sysOrgList)).collect(Collectors.toList());
        return result;
    }

    /**
     * 将权限转换为带有子级的权限对象
     * 当找不到子级权限的时候map操作不会再递归调用covert
     */
    private SysOrgNode covert(SysOrg sysOrg, List<SysOrg> sysOrgNodeList) {
        SysOrgNode node = new SysOrgNode();
        BeanUtils.copyProperties(sysOrg, node);
        List<SysOrgNode> children = sysOrgNodeList.stream()
                .filter(subSysOrg -> subSysOrg.getParentid().equals(sysOrg.getOrgid()))
                .map(subSysOrg -> covert(subSysOrg, sysOrgNodeList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}
